package chaowan.Controller;
import chaowan.Service.GoodsCategoryService;
import chaowan.pojo.GoodsCategory;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/category")
public class GoodsCategoryController {

    @Resource
    private GoodsCategoryService goodsCategoryService;

    @GetMapping("/list")
    public String list(Model model) {
        List<GoodsCategory> categories = goodsCategoryService.findAll();

        // 构造 cid → title 的映射，供页面显示父分类名
        Map<Long, String> categoryTitleMap = new HashMap<>();
        for (GoodsCategory category : categories) {
            categoryTitleMap.put(category.getCid(), category.getTitle());
        }

        model.addAttribute("categories", categories);
        model.addAttribute("categoryTitleMap", categoryTitleMap);
        return "category/list";
    }

    @GetMapping("/addForm")
    public String addForm(Model model) {
        model.addAttribute("category", new GoodsCategory());

        List<GoodsCategory> categories = goodsCategoryService.findAll();
        model.addAttribute("categoryList", categories);

        return "category/add";
    }

    @PostMapping("/add")
    public String add(GoodsCategory goodsCategory) {
        goodsCategoryService.save(goodsCategory);
        return "redirect:/category/list";
    }

    @GetMapping("/editForm/{cid}")
    public String editForm(@PathVariable Long cid, Model model) {
        GoodsCategory category = goodsCategoryService.findById(cid);
        model.addAttribute("category", category);

        List<GoodsCategory> categories = goodsCategoryService.findAll();
        model.addAttribute("categoryList", categories);

        return "category/edit";
    }

    @PostMapping("/update")
    public String update(GoodsCategory goodsCategory) {
        goodsCategoryService.update(goodsCategory);
        return "redirect:/category/list";
    }

    @GetMapping("/delete/{cid}")
    public String delete(@PathVariable Long cid) {
        goodsCategoryService.deleteById(cid);
        return "redirect:/category/list";
    }
}
